package toy.keli.picmap.adapter;

import android.graphics.Point;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import toy.keli.picmap.R;
import toy.keli.picmap.model.def;
import toy.keli.picmap.model.system;
import toy.keli.picmap.model.types.PhotoItem;

public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.InnerHolder> {
    public static final String TAG = "ImageListAdapter";
    private List<Object> mDatas = new ArrayList<>();
    private List<PhotoItem> selectedImages = new ArrayList<>(); // 已经选择的图片集合
    private List<View> picViews = new ArrayList<>(); //
    public  int rowSize=4;

    public List<PhotoItem> getSelectedImages() {
        return selectedImages;
    }

    public void setSelectedImage(PhotoItem img) {
        selectedImages.add(img);
    }
    public boolean setSelectedImages(List<PhotoItem> a) {
        selectedImages.clear();
        selectedImages.addAll(a);
        return true;
    }
    private int selectMaxImages=9;
    boolean enableSelect=false;


    public void setSelectMaxImages(int selectMaxImages) {
        this.selectMaxImages = selectMaxImages;
    }

    public void setRowSize(int rowSize) {
        this.rowSize = rowSize;
    }

    @Override
    public ImageListAdapter.InnerHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        Log.d(TAG, "onCreateViewHolder...");
        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_photo, viewGroup, false);
        Point point = system.getScreenSize(itemView.getContext());
        if(viewType== DATE) {
            RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(point.x, 150);
            itemView.setLayoutParams(layoutParams);
        }else{
            RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(point.x/rowSize-1, point.x/rowSize-1);
            itemView.setLayoutParams(layoutParams);
        }
        picViews.add(itemView);
        return new InnerHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ImageListAdapter.InnerHolder innerHolder, final int i) {
        Log.d(TAG, "onBindViewHolder...");
        View itemView = innerHolder.itemView;

        ImageView imageItem = itemView.findViewById(R.id.iv_images);
        final CheckBox checkBox = itemView.findViewById(R.id.bt_is_selected);
        final View coverView = itemView.findViewById(R.id.image_cover);
        TextView textView = itemView.findViewById(R.id.date);
        Object p=mDatas.get(i);
        PhotoItem pi = null;
        if(getItemViewType(i)==DATE) {
            textView.setText((String) p);
            textView.setVisibility(View.VISIBLE);
            imageItem.setVisibility(View.GONE);
            return;
        }

        pi = (PhotoItem) p;
        Glide.with(imageItem.getContext()).load(pi.getPath()).into(imageItem);
        if (pi.isSelected()) {
            checkBox.setButtonDrawable(R.drawable.ic_selected);
            coverView.setVisibility(View.VISIBLE);
        } else {
            coverView.setVisibility(View.GONE);
            checkBox.setButtonDrawable(R.drawable.ic_no_select);
        }

        if(enableSelect){
            coverView.setEnabled(true);
            checkBox.setEnabled(true);
            checkBox.setVisibility(View.VISIBLE);
        }

        imageItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemEvents.onClick(getRealyIndex(i));
            }
        });
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSelect(itemView, i);
            }
        });
        //长按
        imageItem.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                setEnableSelect(true);
                onSelect(itemView, i);
                return true;
            }
        });
        // 3.实现挑选照片时右上角数目的动态变化 外部设置UI
    }

    private static final int DATE = 1;
    private static final int PHOTO = 0;
    //实现带日期分组的相册展示（ RecyclerView 多布局实现 ) https://blog.csdn.net/qq_39121188/article/details/114818641
    @Override
    public int getItemViewType(int position) {
        //return 的是一个标识，由自己定义一个不重复的数字即可
        Object e=mDatas.get(position);
        if (e instanceof String) {
            return DATE;
        } else {
            return PHOTO;
        }
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if(manager instanceof GridLayoutManager) {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return getItemViewType(position) == DATE ? gridManager.getSpanCount() : 1;
                }
            });
        }
    }
    //
    public void onSelect(View v ,int i){
        final CheckBox checkBox = v.findViewById(R.id.bt_is_selected);
        final View coverView = v.findViewById(R.id.image_cover);
        PhotoItem pi=(PhotoItem)mDatas.get(i);

        // 图片点击后，若当前图片被选择，则应移除被选择图片集合，然后恢复图层
        if (pi.isSelected()) {
            pi.setSelected(false);
            selectedImages.remove(pi);
            coverView.setVisibility(View.GONE);
            checkBox.setButtonDrawable(R.drawable.ic_no_select);
        } else {
            // 3.1 判断已选择的是否大于最大数量
            if (selectedImages.size() >= selectMaxImages) {
                Toast.makeText(checkBox.getContext(), "你最多只能选择" + selectMaxImages + "个图片或视频", Toast.LENGTH_SHORT).show();
                // 结束
                return;
            }
            // 若当前图片没有选择，则应被选择，然后设置图层
            pi.setSelected(true);
            selectedImages.add(pi);
            checkBox.setButtonDrawable(R.drawable.ic_selected);
            coverView.setVisibility(View.VISIBLE);
        }
        itemEvents.onSelect(getRealyIndex(i),selectedImages.size());
    }

    //图片的index
    public void setEnableSelect(int i){
        if(!enableSelect) setEnableSelect(true);
        i=idMap.flip().get(String.valueOf(i)).toInt();
        View itemView=picViews.get(i);
        onSelect(itemView, i);
    }
    public boolean setEnableSelect(Boolean enable){
        enableSelect=enable;
        if(enable) {
            for (int i = 0; i < picViews.size(); i++) {
                View itemView = picViews.get(i);
                if (getItemViewType(i) == DATE) continue;
                itemView.findViewById(R.id.bt_is_selected).setVisibility(View.VISIBLE);
                itemView.findViewById(R.id.image_cover).setVisibility(View.VISIBLE);
            }
        }else{
            selectedImages.clear();
            for(int i=0;i<picViews.size();i++){
                View itemView=picViews.get(i);
                CheckBox checkBox = itemView.findViewById(R.id.bt_is_selected);
                checkBox.setVisibility(View.GONE);
                checkBox.setButtonDrawable(R.drawable.ic_no_select);
                itemView.findViewById(R.id.image_cover).setVisibility(View.GONE);
            }
        }
        return true;
    }


    public ItemEvents itemEvents;



    public interface ItemEvents {
        void onClick(int i);
        void onSelect(int i,int count);
        void onChange(boolean b);
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    def idMap=new def();
    int getRealyIndex(int i){
        return idMap.get(""+i).toInt();
    }
    public void setData(List<PhotoItem> datas) {
        mDatas.clear();
        String data="";
        for(int i=0;i<datas.size();i++){
            PhotoItem v=datas.get(i);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH时");
            String d=formatter.format(v.getCreateTime());
            if(!data.equals(d)) mDatas.add(d);
            idMap.set(mDatas.size(),i);
            mDatas.add(v);
            data=d;
        }
        //mDatas.addAll(datas);
        notifyDataSetChanged();
    }


    public class InnerHolder extends RecyclerView.ViewHolder {
        public InnerHolder(View itemView) {
            super(itemView);
        }
    }
}